<template>
  <div class="inventory-report">
    <ArtTableHeader
      title="库存报表"
      :total="tableData.total"
      @refresh="handleRefresh"
    >
      <template #search>
        <InventoryReportSearch @search="handleSearch" @reset="handleReset" />
      </template>

      <template #extra>
        <ElButton type="success" @click="handleExport">
          <ElIcon><Download /></ElIcon>
          导出报表
        </ElButton>
      </template>
    </ArtTableHeader>

    <ArtTable
      :columns="columns"
      :data="tableData.list"
      :loading="tableLoading"
      :pagination="pagination"
      @page-change="handlePageChange"
    >
      <template #warehouseName="{ row }">
        <span>{{ getWarehouseName(row.warehouseId) }}</span>
      </template>

      <template #areaName="{ row }">
        <span>{{ getAreaName(row.areaId) }}</span>
      </template>

      <template #quantity="{ row }">
        <ElTag :type="getQuantityType(row.quantity)">
          {{ row.quantity }}
        </ElTag>
      </template>

      <template #status="{ row }">
        <ElTag :type="row.quantity > 0 ? 'success' : 'danger'">
          {{ row.quantity > 0 ? "有库存" : "无库存" }}
        </ElTag>
      </template>
    </ArtTable>

    <!-- 统计图表 -->
    <div class="report-charts">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElCard title="库存分布">
            <div ref="inventoryChartRef" style="height: 300px"></div>
          </ElCard>
        </ElCol>
        <ElCol :span="12">
          <ElCard title="库存趋势">
            <div ref="trendChartRef" style="height: 300px"></div>
          </ElCard>
        </ElCol>
      </ElRow>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { Download } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useTable } from "@/composables/useTable";
import { useWmsStore } from "@/store/modules/wms";
import InventoryReportSearch from "./components/InventoryReportSearch.vue";
import type { WMS } from "@/types/wms";

defineOptions({ name: "InventoryReport" });

// 使用WMS store
const wmsStore = useWmsStore();

// 表格配置
const columns = [
  { prop: "itemName", label: "商品名称", minWidth: 150 },
  { prop: "skuName", label: "SKU名称", minWidth: 150 },
  { prop: "warehouseName", label: "仓库", width: 120, slot: "warehouseName" },
  { prop: "areaName", label: "库区", width: 100, slot: "areaName" },
  { prop: "quantity", label: "库存数量", width: 100, slot: "quantity" },
  { prop: "availableQuantity", label: "可用数量", width: 100 },
  { prop: "allocatedQuantity", label: "分配数量", width: 100 },
  { prop: "frozenQuantity", label: "冻结数量", width: 100 },
  { prop: "status", label: "状态", width: 80, slot: "status" },
  { prop: "updateTime", label: "更新时间", width: 160 },
];

// 模拟API调用
const fetchInventoryReport = async (params: any) => {
  // 这里应该调用真实的API
  return new Promise<{ list: any[]; total: number }>((resolve) => {
    setTimeout(() => {
      const mockData = Array.from({ length: 20 }, (_, index) => ({
        id: index + 1,
        itemName: `商品${index + 1}`,
        skuName: `SKU${index + 1}`,
        warehouseId: 1,
        areaId: 1,
        quantity: Math.floor(Math.random() * 1000),
        availableQuantity: Math.floor(Math.random() * 800),
        allocatedQuantity: Math.floor(Math.random() * 100),
        frozenQuantity: Math.floor(Math.random() * 50),
        updateTime: new Date().toLocaleString(),
      }));

      resolve({
        list: mockData,
        total: 100,
      });
    }, 1000);
  });
};

// 使用表格组合式函数
const { tableData, tableLoading, pagination, handlePageChange, refreshTable } =
  useTable({
    fetchData: fetchInventoryReport,
    defaultPageSize: 20,
  });

// 搜索参数
const searchParams = ref<WMS.InventoryQueryParams>({});

// 图表引用
const inventoryChartRef = ref();
const trendChartRef = ref();

// 获取仓库名称
const getWarehouseName = (warehouseId: number) => {
  const warehouse = wmsStore.warehouseMap[warehouseId];
  return warehouse?.warehouseName || "-";
};

// 获取库区名称
const getAreaName = (areaId: number) => {
  const area = wmsStore.areaMap[areaId];
  return area?.areaName || "-";
};

// 获取数量标签类型
const getQuantityType = (quantity: number) => {
  if (quantity > 100) return "success";
  if (quantity > 50) return "warning";
  return "danger";
};

// 搜索处理
const handleSearch = (params: WMS.InventoryQueryParams) => {
  searchParams.value = params;
  refreshTable(params);
};

// 重置搜索
const handleReset = () => {
  searchParams.value = {};
  refreshTable();
};

// 刷新
const handleRefresh = () => {
  refreshTable(searchParams.value);
};

// 导出报表
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 初始化图表
const initCharts = () => {
  // 这里可以使用 ECharts 或其他图表库
  console.log("初始化图表...");
};

// 初始化
onMounted(async () => {
  // 加载基础数据
  await wmsStore.getWarehouseList();

  // 加载表格数据
  refreshTable();

  // 初始化图表
  initCharts();
});
</script>

<style lang="scss" scoped>
.inventory-report {
  padding: 20px;

  .report-charts {
    margin-top: 20px;
  }

  :deep(.art-table-header) {
    margin-bottom: 16px;
  }
}
</style>
